import { fetchCors } from '../../common';
import { ApiResponse, Lyrics, Resource } from '../types';
import { getAuthToken } from './auth';

export async function getLyrics(id: string, syllable: boolean, country?: string): Promise<Resource<Lyrics> | null> {
	country ??= location.pathname.split('/')[1];

	const res = await fetchCors(`https://amp-api.music.apple.com/v1/catalog/${country}/songs/${id}/${syllable ? 'syllable-lyrics' : 'lyrics'}`, {
		headers: {
			'Origin': 'https://music.apple.com',
			'Referer': 'https://music.apple.com/',
			'Authorization': `Bearer ${await getAuthToken()}`
		}
	});

	if (res.status === 404) return null;

	const lyrics = await res.json<ApiResponse<Lyrics>>();
	return lyrics.data[0];
}
